package com.fuxi.cloud.common.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fuxi.cloud.common.annotation.JimuLoginRequired;
import com.fuxi.cloud.common.util.oConvertUtils;
import com.fuxi.cloud.common.vo.Result;
import com.fuxi.cloud.config.client.JmReportTokenClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

public class JimuReportInterceptor implements HandlerInterceptor {
    private static final Logger log = LoggerFactory.getLogger(JimuReportInterceptor.class);

    @Autowired
    private JmReportTokenClient jimuTokenClient;

    @Value("${jeecg.jmreport.customPrePath:}")
    private String customPrePath;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (!(handler instanceof HandlerMethod))
            return true;
        request.setAttribute("customPrePath", this.customPrePath);
        HandlerMethod handlerMethod = (HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        JimuLoginRequired jimuLoginRequired = method.<JimuLoginRequired>getAnnotation(JimuLoginRequired.class);
        String str = filterUrl(request.getRequestURI().substring(request.getContextPath().length()));
        log.debug("JimuReportInterceptor check requestPath = " + str);
        if (ObjectUtil.isNotEmpty(jimuLoginRequired) && jimuLoginRequired.required() &&
                !verifyToken(request)) {
            log.error("+ request.getMethod() + "+ str);
            backError(response);
            return false;
        }
        return true;
    }

    private boolean verifyToken(HttpServletRequest request) {
        return this.jimuTokenClient.verifyToken(request);
    }

    private String filterUrl(String requestPath) {
        String str = "";
        if (oConvertUtils.isNotEmpty(requestPath)) {
            str = requestPath.replace("\\", "/");
            str = str.replace("//", "/");
            if (str.indexOf("//") >= 0)
                str = filterUrl(str);
        }
        return str;
    }

    private void backError(HttpServletResponse response) {
        PrintWriter printWriter = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        response.setHeader("auth", "fail");
        try {
            printWriter = response.getWriter();
            Result var3 = Result.error("Token校验失败，无权限访问！");
            printWriter.print(JSON.toJSON(var3));
        } catch (IOException iOException) {
            log.error(iOException.getMessage());
        } finally {
            if (printWriter != null)
                printWriter.close();
        }
    }
}


